
import 'package:flutter/material.dart';

class DBStarRating extends StatefulWidget {
  final double rating;
  final double maxRating;
  final int count;
  final double size;
  final Color unSelectedColor;
  final Color selectedColor;

  const DBStarRating({
    super.key,
    required this.rating,
    this.maxRating = 5,
    this.count = 5,
    this.size = 30,
    this.unSelectedColor = Colors.grey,
    this.selectedColor = Colors.red,
  });

  @override
  State<DBStarRating> createState() => _DBStarRatingState();
}

class _DBStarRatingState extends State<DBStarRating> {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(widget.count, (index) {
        double starValue = (index + 1) / widget.count;
        double fillRatio =
            (widget.rating / widget.maxRating) - (index / widget.count);

        if (fillRatio <= 0) {
          return Icon(
            Icons.star_border,
            color: widget.unSelectedColor,
            size: widget.size,
          );
        }

        return Stack(
          children: [
            // 背景星星（未选中）
            Icon(
              Icons.star_border,
              color: widget.unSelectedColor,
              size: widget.size,
            ),
            // 前景星星（选中部分）
            if (fillRatio > 0)
              SizedBox(
                width: widget.size,
                height: widget.size,
                child: ClipRect(
                  child: Align(
                    alignment: Alignment.centerLeft,
                    widthFactor: fillRatio.clamp(0.0, 1.0),
                    child: Icon(
                      Icons.star,
                      color: widget.selectedColor,
                      size: widget.size,
                    ),
                  ),
                ),
              ),
          ],
        );
      }),
    );
  }
}
